﻿using System;

using System.Collections.Generic;
using System.Text;
using System.IO;

namespace gpsmid_wince.util {
	class FileTile : Tile {
		sbyte zl;
		Tile tile = null;
		volatile bool inLoad = false;
		private static Logger logger = Logger.getInstance("FileTile", Logger.DEBUG);

		public FileTile(JavaDataInputStream dis, int deep, sbyte zl) {
			minLat = dis.readFloat();
			minLon = dis.readFloat();
			maxLat = dis.readFloat();
			maxLon = dis.readFloat();
			fileId = dis.readShort();
			this.zl = zl;

			isDataReady();
		}

		public override void paint(PaintContext pc, sbyte layer) {
			if(tile!=null)
			tile.paint(pc, layer);
		}

		public override void walk(PaintContext pc, int opt) {
			throw new NotImplementedException();
		}

		public override bool cleanup(int level) {
			if (!inLoad && tile != null) {
				if (lastUse > level) {
					tile = null;
					return true;
				}
			}
			return false;
		}

		private bool isDataReady() {
			if (!inLoad && tile == null) {
				//Trace.getInstance().getDictReader().add(this,this);
				readFileTile();
				return false;
			}
			if (inLoad) {
				return false;
			}
			if (tile != null) {
				return true;
			}
			return true;

		}

		private void readFileTile() {
			FileTile tt = this;

			FileStream is_ = File.OpenRead(DictReader.basename + @"/d" + tt.zl + tt.fileId + ".d");
			logger.debug("Loading file "+is_.Name );
			if (is_ == null) {
				throw new IOException("File not found /d" + tt.zl + "/" + tt.fileId + ".d");
			}
			JavaDataInputStream ds = new JavaDataInputStream(is_);
			if (!"DictMid".Equals(ds.readUTF())) {
				throw new IOException("not a DictMid-file");
			}
			sbyte type = ds.readByte();
			Tile dict = null;
			switch (type) {
				case 1:
					dict = new SingleTile(ds, 1, tt.zl);
					break;
				case 2:
					dict = new ContainerTile(ds, 1, tt.zl);
					break;
				case 3:
					// empty tile;
					return;
				case 4:
					dict = new FileTile(ds, 1, tt.zl);
					break;
				default:
					break;
			}

			ds.close();

			tt.tile = dict;
			tt.inLoad = false;
			tt.lastUse = 0;
			inLoad = false;
			//trace.newDataReady();
			/*
			if (notifyReady != null) {
				synchronized(notifyReady) {
					notifyReady.notifyAll();
				}
			}*/
		}

	}
}
